//
//  TheMapViewController.m
//  Product
//
//  Created by zz on 16/1/7.
//  Copyright © 2016年 Aim. All rights reserved.
//

#import "TheMapViewController.h"
#import <MapKit/MapKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
//#import "QianDaoViewController.h"
#import <AMapLocationKit/AMapLocationKit.h>
@interface TheMapViewController ()<MKMapViewDelegate,MAMapViewDelegate,AMapSearchDelegate,UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate,AMapLocationManagerDelegate>
{
    MAMapView *_mapView;
    AMapSearchAPI *_search;
    UISearchBar * searchBarMian;
    UITableView * pullTableView;
    NSMutableArray* listArray;
    MAUserLocation * userLocation1;
    AMapLocationManager *locationManager;
    MAPointAnnotation *pointAnnotation;
    
    
}
@property (nonatomic, strong) MAAnnotationView *userLocationAnnotationView;
@end

@implementation TheMapViewController


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _mapView = nil;
    locationManager.delegate = nil;
    [locationManager stopUpdatingLocation];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title= @"地图";
    self.navigationController.navigationBarHidden = YES;
    //    [MyNavigationVC createBackBtn:self];
    [self kaiQiDingWei];
}
-(void)kaiQiDingWei{
    [MAMapServices sharedServices].apiKey = @"a067cb02665ee78786d840975116df60";
    [AMapSearchServices sharedServices].apiKey = @"a067cb02665ee78786d840975116df60";
    [AMapLocationServices sharedServices].apiKey = @"a067cb02665ee78786d840975116df60";
    //地图初始化
    CGRect frame = self.view.frame;
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 20,frame.size.width,frame.size.height-20)];
    _mapView.delegate = self;//代理
    
    //定位用户位置的模式
    _mapView.userTrackingMode = 0;
    _mapView.showsScale = NO;
    _mapView.showsCompass = NO;
    _mapView.centerCoordinate =CLLocationCoordinate2DMake([self.lati floatValue],[self.lonti floatValue]);
    NSLog(@"-=-=-=-=%f/%f",[self.lati floatValue],[self.lonti floatValue]);
    [_mapView setZoomLevel:16 animated:YES];//当前缩放级别，百米级
    _mapView.showsUserLocation = YES;
    
#pragma mark==暂时隐藏
    
    [self.view addSubview:_mapView];
    
    //定位代理初始化
    locationManager = [[AMapLocationManager alloc] init];
    locationManager.delegate = self;
    //    [locationManager startUpdatingLocation];
    //大头针创建
    pointAnnotation = [[MAPointAnnotation alloc] init];
    
    
    [locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        
        
        //        NSLog(@"location:%@", location);// 时间
        
        if (regeocode)
        {
            
            //            NSLog(@"reGeocode:%@%@",regeocode, regeocode.formattedAddress);//地理位置
            //            NSString  *formattedAddress =regeocode.formattedAddress;
            //            NSString *township =regeocode.township;
            //            pointAnnotation.coordinate = CLLocationCoordinate2DMake(userLocation.coordinate.latitude,userLocation.coordinate.longitude);
            //            NSString *province = regeocode.province;
            //            NSString *city = regeocode.city;
            //            NSString *area = regeocode.district;
            //            NSString *longArea = [NSString stringWithFormat:@"%@%@%@%@",province,city,area,formattedAddress];
            
            pointAnnotation.coordinate = CLLocationCoordinate2DMake([self.lati floatValue],[self.lonti floatValue]);
            pointAnnotation.title = @"当前位置";
            //            pointAnnotation.subtitle = longArea;
#pragma mark ==添加大头针
            [_mapView addAnnotation:pointAnnotation];
            
            [locationManager stopUpdatingLocation];
        }
    }];
    
    UIButton *back = [[UIButton alloc] initWithFrame:CGRectMake(10, 30, 30, 30)];
    back.layer.cornerRadius = 30/2;
    back.layer.masksToBounds = YES;
    [back setImage:[UIImage imageNamed:@"sao"] forState:UIControlStateNormal];
    back.backgroundColor = [UIColor whiteColor];
    [back setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    back.titleLabel.font = [UIFont systemFontOfSize:16];
    [back addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:back];
    _mapView.scaleOrigin = CGPointMake(_mapView.scaleOrigin.x, back.frame.origin.x+back.frame.size.height+12);//比例尺位置
    
    
}

- (void)mapViewDidStopLocatingUser:(MAMapView *)mapView
{
    [locationManager stopUpdatingLocation];
    
}


- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    searchBarMian.text = @"";
    [searchBarMian resignFirstResponder];
}
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
        annotationView.animatesDrop = YES;        //设置标注动画显示，默认为NO
        annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
        annotationView.pinColor = MAPinAnnotationColorRed;
        return annotationView;
    }
    return nil;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //生成一个表视图
}

-(void)addSearchScreen{
    
    searchBarMian.hidden = NO;
    //初始化检索对象
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
    
    //构造AMapPOIAroundSearchRequest对象，设置周边请求参数
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:userLocation1.coordinate.latitude longitude:userLocation1.coordinate.longitude];
    request.keywords = searchBarMian.text;
    // types属性表示限定搜索POI的类别，默认为：餐饮服务|商务住宅|生活服务
    // POI的类型共分为20种大类别，分别为：
    //     汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|
    //     医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|
    //     交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
    request.types = @"汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";
    request.sortrule = 0;
    request.requireExtension = YES;
    
    //发起周边搜索
    [_search AMapPOIAroundSearch: request];
    
}
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error{
    NSLog(@"%@",error);
}

//实现POI搜索对应的回调函数
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if(response.pois.count == 0)
    {
        pullTableView.hidden = YES;
        return;
    }
    //通过 AMapPOISearchResponse 对象处理搜索结果
    NSString *strCount = [NSString stringWithFormat:@"count: %ld",(long)response.count];
    NSString *strSuggestion = [NSString stringWithFormat:@"Suggestion: %@", response.suggestion];
    NSString *strPoi = @"";
    listArray =  [NSMutableArray arrayWithCapacity:0];
    for (AMapPOI *p in response.pois) {
        strPoi = [NSString stringWithFormat:@"%@\nPOI: %@", strPoi, p.description];
        
        [listArray addObject:p];
    }
    
    [pullTableView reloadData];
    NSString *result = [NSString stringWithFormat:@"%@ \n %@ \n %@", strCount, strSuggestion, strPoi];
    NSLog(@"Place: %@", result);
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return listArray.count+1;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    }
    if (indexPath.row == 0) {
        cell.textLabel.text = userLocation1.title;
        cell.detailTextLabel.text = userLocation1.subtitle;
    }else{
        AMapPOI * p = listArray[indexPath.row-1];
        cell.textLabel.text = p.name;
        cell.detailTextLabel.text = p.address;
    }
    return cell;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //跳转传值给签到界面
    switch (indexPath.row) {
        case 0:
            //            [self.delegate theView:self addRess:[NSString stringWithFormat:@"%@%@",userLocation1.title,userLocation1.subtitle]];
            break;
        default:{
            AMapPOI * p = listArray[indexPath.row-1];
            [self.delegate theView:self addRess:[NSString stringWithFormat:@"%@%@%@%@",p.province,p.city,p.district,p.address]];
            break;
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
    
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [searchBarMian resignFirstResponder];
}

@end
